package com.xjm.i1.utils;

import cn.hutool.core.lang.Filter;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;

/**
 * 扩展字符串处理工具类
 **/
public class StrUtils {

    public static final int BUFFER_SIZE = 4096;

    /**
     * 将多个空格去除分开并返回ArrayList<Double>
     * @param source 源字符串
     * @param len 返回值初始化长度，默认8
     * @return 空格分离List
     * */
    public static ArrayList<Double> splitBlankToList(String source, int len) {
        if (len <1) {
            len = 8;
        }
        return filter(source, len, (c) -> {
            return !CharUtil.isBlankChar(c);
        });
    }

    /**
     * 将多个空格去除分开并返回Double[]
     * @param source 源字符串
     * @param len 返回值初始化长度，默认8
     * @return 空格分离数组
     * */
    public static Double[] splitBlankToArray(String source, int len) {
        ArrayList<Double> list = splitBlankToList(source, len);
        return list.toArray(new Double[list.size()]);
    }

    /**
     * 去除所有空格
     * */
    public static String rmBlank(String source) {
        return StrUtil.cleanBlank(source);
    }

    /**
     * 将double转为string百分比
     * */
    public static String covertPercent(double source) {
        return NumberUtil.decimalFormat("#.#%", source);
    }

    /**
     * 将inputStream转为String输出
     * @param in inputstream
     * @param charset 转换编码
     * @return String 文本
     * */
    public static String copyToString(InputStream in, Charset charset) throws IOException {
        if (in == null) {
            return "";
        }

        StringBuilder out = new StringBuilder(BUFFER_SIZE);
        InputStreamReader reader = new InputStreamReader(in, charset);
        char[] buffer = new char[BUFFER_SIZE];
        int charsRead;
        while ((charsRead = reader.read(buffer)) != -1) {
            out.append(buffer, 0, charsRead);
        }
        return out.toString();
    }

    public static ArrayList<Double> filter(CharSequence str, int len, Filter<Character> filter) {
        ArrayList<Double> res = new ArrayList(len);
        if (str != null && filter != null) {
            int strLen = str.length();
            StringBuilder sb = new StringBuilder(strLen);
            char lastChar = ' ';
            for(int i = 0; i < strLen; ++i) {
                char c = str.charAt(i);
                if (filter.accept(c)) {
                    sb.append(c);
                } else {
                    if (!CharUtil.isBlankChar(lastChar)) {
                        String s = sb.toString();
                        sb.delete(0, sb.length());
                        if (!StrUtil.isEmpty(s)) {
                            res.add(Double.valueOf(s));
                        }
                    }
                }
                lastChar = c;
            }
        }
        return res;
    }
}
